package com.xl6667.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xl6667.constants.RedisConstants;
import com.xl6667.domain.ResponseResult;
import com.xl6667.domain.dto.BlogUserLoginDto;
import com.xl6667.domain.dto.UserInfoDto;
import com.xl6667.domain.entity.LoginUser;
import com.xl6667.domain.entity.User;
import com.xl6667.enums.AppHttpCodeEnum;
import com.xl6667.filter.SmsCodeAuthenticationToken;
import com.xl6667.mapper.UserMapper;
import com.xl6667.service.BlogLoginService;
import com.xl6667.service.UserService;
import com.xl6667.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
* @author 熊磊
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2024-03-15 19:28:50
*/
@Service
@Slf4j
public class BlopLoginServiceImpl extends ServiceImpl<UserMapper, User>
    implements BlogLoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private UserService userService;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或吗密码有误");
        }
        //获取查询的用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //获取用户id
        String id = loginUser.getUser().getId().toString();
        //生成Jwt
        String jwt = JwtUtil.createJWT(id);
        //将用户信息存入redis
        redisCache.setCacheObject("blogLogin"+id,loginUser, RedisConstants.LOGIN_CACHE_TIME,TimeUnit.HOURS);
        //封装token和user
        UserInfoDto dto = BeanCopyUtil.copyBean(loginUser.getUser(), UserInfoDto.class);
        BlogUserLoginDto blogUserLoginDto = new BlogUserLoginDto(jwt, dto);


        return ResponseResult.okResult(blogUserLoginDto);
    }
    @Override
    public ResponseResult loginSms(String phonenumber,String code) {
        SmsCodeAuthenticationToken smsCodeAuthenticationToken = new SmsCodeAuthenticationToken(phonenumber);

        Authentication authenticate = authenticationManager.authenticate(smsCodeAuthenticationToken);

        if (Objects.isNull(authenticate)){
            throw new RuntimeException("手机号或验证码有误");
        }
        //获取查询的用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //获取用户id
        String id = loginUser.getUser().getId().toString();
        //生成Jwt
        String jwt = JwtUtil.createJWT(id);
        //将用户信息存入redis
        redisCache.setCacheObject("blogLogin"+id,loginUser);
        //封装token和user
        UserInfoDto dto = BeanCopyUtil.copyBean(loginUser.getUser(), UserInfoDto.class);
        BlogUserLoginDto blogUserLoginDto = new BlogUserLoginDto(jwt, dto);


        return ResponseResult.okResult(blogUserLoginDto);
    }

    @Override
    public ResponseResult logout() {
        //从SecurityContextHolder中获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //获取用户id
        String id = loginUser.getUser().getId().toString();
        //将用户信息从redis中删除;
        redisCache.deleteObject("blogLogin"+id);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult getSms(String phonenumber) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhonenumber,phonenumber);
        User user = userService.getOne(queryWrapper);
        if (Objects.isNull(user)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR,"用户未注册");
        }

        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        log.info("验证码为："+code);
        SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phonenumber,code);

        redisCache.setCacheObject("smscode:"+phonenumber,code,5, TimeUnit.MINUTES);
        return ResponseResult.okResult("发送成功");
    }


}




